﻿using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Globalization;
using System.Linq;
using System.ServiceModel;
using System.Text;

namespace Tradex.Connectivity {
    
    /// <summary>
    /// The ConnectorApiHost class hosts the ConnectorApi (IConnectorApi instance) in WCF and thus
    /// exposes the a ConnectorName to control from the control terminal.
    /// </summary>
    public sealed class ConnectivityApiHost : IDisposable {

        /// <summary>
        /// Constructor taking all necessary parameters.
        /// </summary>
        /// <param name="target"></param>
        public ConnectivityApiHost(IConnectivityApi target) {
            _ServiceHost = new ServiceHost(target);
            _ServiceHost.AddServiceEndpoint(
                typeof(IConnectivityApi),
                new NetNamedPipeBinding(NetNamedPipeSecurityMode.None) { MaxReceivedMessageSize = 65536 * 64 },
                GetConnectivityUrl()
            );
            _ServiceHost.Open();
        }

        ServiceHost _ServiceHost;

        /// <inheritdoc />
        public void Dispose() {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        void Dispose(bool disposing) {
            if (disposing) {
                if (_ServiceHost != null) {
                    _ServiceHost.Close();
                    _ServiceHost = null;
                }
            }
        }

        /// <summary>
        /// This is the URL string of the ControlAPI. It is static and well known (only one control instance can ever on a server).
        /// </summary>
        /// <returns></returns>
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1055:UriReturnValuesShouldNotBeStrings")]
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")]
        public static string GetConnectivityUrl() {
            return "net.pipe://localhost/Tradex.ConnectivityService/ConnectorTarget.svs";
        }

    }

}
